package com.tokenmaster.aitrade.common.system;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;

/**
 * 对接阿里云MNS
 * 
 * @author glf
 */
public class MnsComponent {

	private Logger logger = Logger.getLogger(this.getClass());

	private static MnsComponent instance = null;

	private static CloudAccount account = null;

	private static MNSClient client = null;

	private String accessKeyId = "";
	private String accessKeySecret = "";
	private String endpoint = "";
	private String queueName = "";

	private MnsComponent() {

		// 从配置文件中读取mns配置信息
		Properties propfile = new Properties();
		try {
			InputStream inputStream = new BufferedInputStream(new FileInputStream("mns.properties"));
			propfile.load(inputStream);

			accessKeyId = propfile.getProperty("AccessKeyId");
			accessKeySecret = propfile.getProperty("AccessKeySecret");
			endpoint = propfile.getProperty("Endpoint");
			queueName = propfile.getProperty("QueueName");

			inputStream.close();

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		account = new CloudAccount(accessKeyId, accessKeySecret, endpoint);
		client = account.getMNSClient();
	}

	public static synchronized MnsComponent getInstance() {
		if (instance == null) {
			instance = new MnsComponent();
		}
		return instance;
	}

	/**
	 * 发送消息
	 * 
	 * @author glf
	 * @param content
	 * @param queueName
	 * @throws Exception
	 */
	public void sendMessage(String content) throws Exception {
		try {
			CloudQueue queue = getQueue();
			Message message = new Message();
			message.setMessageBody(content);
			Message putMsg = queue.putMessage(message);
			// logger.info("发送消息成功，发送内容为{}，消息ID为{}", content,
			// putMsg.getMessageId());
		} catch (Exception e) {
			logger.error("从队列" + queueName + "发送消息失败，消息内容为" + content, e);
			throw e;
		}
	}

	/**
	 * 获取队列中的消息并删除
	 * 
	 * @author glf
	 * @param queueName
	 * @return
	 * @throws Exception
	 */
	public String receiveMessageWithDelete() throws Exception {
		try {
			CloudQueue queue = getQueue();
			Message popMsg = queue.popMessage();
			if (popMsg != null) {
				// logger.info("接收消息成功，消息内容为{}，消息ID为{}",
				// popMsg.getMessageBodyAsString(), popMsg.getMessageId());
				// 删除已经取出消费的消息
				queue.deleteMessage(popMsg.getReceiptHandle());
				logger.info("删除消息成功");
				return popMsg.getMessageBodyAsString();
			} else {
				logger.info("队列中没有消息");
				return null;
			}
		} catch (Exception e) {
			logger.error("从队列" + queueName + "接收消息失败", e);
			throw e;
		}
	}

	/**
	 * 删除队列中的对应消息
	 * 
	 * @author glf
	 * @param queueName
	 * @param msgHandle
	 * @throws Exception
	 */
	public void deleteMessage(String msgHandle) throws Exception {
		try {
			CloudQueue queue = getQueue();
			// 删除已经取出消费的消息
			queue.deleteMessage(msgHandle);
		} catch (Exception e) {
			logger.error("从队列" + queueName + "删除消息失败", e);
			throw e;
		}
	}

	/**
	 * 获取队列对象
	 * 
	 * @author glf
	 * @param queueName
	 * @return
	 * @throws Exception
	 */
	private CloudQueue getQueue() throws Exception {
		if (!client.isOpen()) {
			account = new CloudAccount(accessKeyId, accessKeySecret, endpoint);
			client = account.getMNSClient();
		}

		CloudQueue queue = client.getQueueRef(queueName);
		if (!queue.isQueueExist()) {
			throw new Exception("队列不存在或已离线");
		}

		return queue;
	}

	/**
	 * test
	 * 
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// SystemConstants.setMnsAccessId("LTAIITebJUkN84HG");
		// SystemConstants.setMnsAccessKey("lJG7RKS1xXCoSJVGDQJODgG8rWIuOg");
		// SystemConstants.setMnsAccountEndpoint("http://1353234872209038.mns.cn-hongkong.aliyuncs.com/");

		MnsComponent component = MnsComponent.getInstance();
		String queueName = "test-bpop-ai-trade";

		// String content = component.receiveMessageWithDelete(queueName);
		// System.out.println("接收到队列中的消息：" + StringUtils.trimToNull(content));
		//
		// component.sendMessage("hello world", queueName);
		// System.out.println("消息发送成功");
		//
		// content = component.receiveMessageWithDelete(queueName);
		// System.out.println("接收到队列中的消息：" + StringUtils.trimToNull(content));
	}

}
